package com.shr.xsunmvc.db;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

import com.shr.xsunmvc.db.mapper.TableMapper;
import com.shr.xsunmvc.db.util.Db2ObjectChangeUtil;

/**
 * 定义一个Model接口，用于使用代码进行简单的数据库操作
 * @author sun haoran
 *
 */
public abstract class Model {
	
	/**
	 * 根据字段名存放value值
	 */
	private Map<String, Object> attributes ; 
	
	/**
	 * 数据库表对应的table
	 */
	private Table table ;
	
	public int save(){
		setAttributes();
		setTable();
		StringBuilder sql = new StringBuilder() ;
		XsunDb.getGenerateSql().forSave(table, attributes, sql);
		int res = XsunDb.save(sql, attributes);
		return res ;
	}

	private void setTable() {
		table = TableMapper.me().getTable(getClass()) ;
	}

	private void setAttributes() {
		try{
			Class<?> clazz =  getClass() ;
			for (Field field : clazz.getFields()){
				String sqlColumnName = Db2ObjectChangeUtil.hump2Underline(field.getName());
				String methodName = Db2ObjectChangeUtil.change2GetMethodName(field.getName());
				Method method = clazz.getMethod(methodName) ;
				Object val = method.invoke(this) ;
				
				attributes.put(sqlColumnName, val) ;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
